package com.lee.bgTask;

import com.lee.bgTask.entity.impl.AbstractTaskEntity;
import com.lee.bgTask.queue.TaskQueue;
import com.lee.bgTask.thread.BgTaskThread;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 任务执行中心
 */
@Component
public class BgTaskExcuteCenter implements InitializingBean {

    @Value("${bgTask.queue.size}")
    private int threads;

    private Map<Integer, TaskQueue> queueMap;

    private Map<Integer, BgTaskThread> threadMap;


    public void init() {
        queueMap = new HashMap<>();
        threadMap = new HashMap<>();
        for (int i = 0; i < threads; i++) {
            TaskQueue queue = new TaskQueue<>();
            BgTaskThread thread = new BgTaskThread(queue);
            queueMap.put(i, queue);
            threadMap.put(i, thread);
        }

    }

    private void checkThread() {
        for (int i = 0; i < queueMap.size(); i++) {
            BgTaskThread thread = threadMap.get(i);
            if (!thread.isAlive()) {
                TaskQueue queue = queueMap.get(i);
                thread = new BgTaskThread(queue);
                threadMap.put(i, thread);
            }
        }
    }

    /**
     * 添加任务
     *
     * @param taskEntity
     */
    public void put(AbstractTaskEntity taskEntity) {
        int index = Math.abs(taskEntity.queueHash()) % threads;
        queueMap.get(index).add(taskEntity);
    }

    /**
     * 取消任务
     *
     * @param taskEntity
     */
    public void remove(AbstractTaskEntity taskEntity) {
        int index = Math.abs(taskEntity.queueHash()) % threads;
        queueMap.get(index).remove(taskEntity);
    }

    /**
     * 清除指定线程已完成任务
     *
     * @param id
     */
    public void clean(Integer id) {
        TaskQueue queue = queueMap.get(id);
        if (queue != null) {
            queue.clean();
        }
    }

    /**
     * 清除指定线程全部任务
     *
     * @param id
     */
    public void cleanAll(Integer id) {
        TaskQueue queue = queueMap.get(id);
        if (queue != null) {
            queue.cleanAll();
        }
    }

    /**
     * 启动任务调动
     */
    public void start() {
        for (BgTaskThread thread : threadMap.values()) {
            thread.start();
        }

        Thread t = new Thread(() -> {
            try {
                Thread.sleep(2000);
                checkThread();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        });
        t.start();
    }

    public Map<Integer, TaskQueue> getQueueMap() {
        return queueMap;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        init();
    }
}
